<?php


namespace models;


use think\Model;

class Article extends Model
{
    protected function special_equal($value){
        if(is_array($value)){
            foreach($value as $k=>$v){
                $value[$k]=$this->special_equal($v);
            }
        }else{
            $value=trim($value);
            if(strpos($value,'=') === 0){
                $value = "'".$value;
            }
        }
        return $value;
    }
    //导出
    public function export($file_path,$data){
        if(empty($data)) return true;

        if(!file_exists($file_path)){
            @mkdir(dirname($file_path),0777,true);
            $excel=new \PHPExcel();
            $sheet=$excel->getActiveSheet();
            $sheet->setTitle('数据');
            foreach (range('A','Z') as $k=>$v){
                $sheet->getColumnDimension($v)->setWidth(20);
            }
            $sheet->setCellValueByColumnAndRow(0, 1,'ID');
            $sheet->setCellValueByColumnAndRow(1, 1,'标题');
            $sheet->setCellValueByColumnAndRow(2, 1,'添加人');

            $write=\PHPExcel_IOFactory::createWriter($excel,'Excel2007');
            $write->save($file_path);
        }

        if(!file_exists($file_path)){
            return false;
        }
        //向excel中追加数据
        $excel=\PHPExcel_IOFactory::load($file_path);
        $sheet=$excel->getActiveSheet();
        $rows=$sheet->getHighestRow();
        $row=$rows+1;
        foreach($data as $key=>$value){
            $value=$this->special_equal($value);

            $sheet->setCellValueByColumnAndRow(0, $row,$value['itemid']);
            $sheet->setCellValueByColumnAndRow(1, $row,$value['title']);
            $sheet->setCellValueByColumnAndRow(2, $row,$value['username']);
            $row++;
        }
        $write=\PHPExcel_IOFactory::createWriter($excel,'Excel2007');
        $write->save($file_path);
        return true;
    }
}